﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Phoenix.Xna.Framework.Properties;

namespace Phoenix.Xna.Framework.Graphics
{
    public class SpriteBatchService : Service, ISpriteBatchService
    {
        private Dictionary<string, SpriteBatchSettings> _settings = new Dictionary<string, SpriteBatchSettings>();

        public SpriteBatchService()
            : base()
        {
            Initialize();
        }

        public SpriteBatchService(string id)
            : base(id)
        {
            Initialize();
        }

        private void Initialize()
        {
            SpriteBatch = new SpriteBatch(Engine.Instance.GraphicsDevice);

            if (Engine.Instance.Services != null)
            {
                Engine.Instance.Services.AddService<ISpriteBatchService>(this);
            }
        }

        #region ISpriteBatchService Members

        public SpriteBatch SpriteBatch { get; private set; }

        public void Begin()
        {
            SpriteBatch.Begin();
        }

        public void Begin(SpriteBlendMode blendMode)
        {
            SpriteBatch.Begin(blendMode);
        }

        public void Begin(SpriteBlendMode blendMode, SpriteSortMode sortMode, SaveStateMode stateMode)
        {
            SpriteBatch.Begin(blendMode, sortMode, stateMode);
        }

        public void Begin(SpriteBlendMode blendMode, SpriteSortMode sortMode, SaveStateMode stateMode, Matrix transformMatrix)
        {
            SpriteBatch.Begin(blendMode, sortMode, stateMode, transformMatrix);
        }

        public void End()
        {
            SpriteBatch.End();
        }

        public void AddSettings(string id, SpriteBatchSettings settings)
        {
            if (_settings.ContainsKey(id))
            {
                throw new ArgumentException(string.Format(Resources.SpriteBatchSettingsAlreadyExistsException, id));
            }

            _settings.Add(id, settings);
        }

        public void RemoveSettings(string id)
        {
            if (_settings.ContainsKey(id))
            {
                _settings.Remove(id);
            }
        }

        public void BeginWithSettings(string id)
        {
            if (_settings.ContainsKey(id))
            {
                SpriteBatchSettings settings = _settings[id];
                Begin(settings.BlendMode, settings.SortMode, settings.StateMode, settings.TransformMatrix);
            }
            else
            {
                Begin();
            }
        }

        #endregion
    }
}
